module.exports = function () {
  const preKeyWork = 'production'
  const preConsoleProps = ['log', 'dir', 'info', 'error', 'warn', 'time', 'timeEnd']
  const preMemberExpressionCalleeobjectName = 'console'
  return {
    name: 'removeConsole',
    visitor: {
      CallExpression(path, state) {
        const { keyWord: keyWord = preKeyWork, isProd: isProd, consoleProps: consoleProps = preConsoleProps } = state.opts
        if (!isProd) return
        const calleeType = path.node.callee.type
        if (calleeType === 'MemberExpression') {
          const calleePropeName = path.node.callee.property.name
          const calleeobjectName = path.node.callee.object.name
          const calleeobjectType = path.node.callee.object.type
          if (
            consoleProps.includes(calleePropeName) &&
            calleeobjectType === 'Identifier' &&
            calleeobjectName === preMemberExpressionCalleeobjectName
          ) {
            const logExplains = path.node.arguments
              .map((item) => item.leadingComments)
              .filter(Boolean)
            const logExplainsStr = logExplains.reduce((pre, item) => {
              pre.push(...item.map(({ value }) => value))
              return pre
            }, [])
            const hasKeyWord = logExplainsStr.some((item) =>
              item.includes(keyWord)
            )
            if (!hasKeyWord) {
              path.remove()
            }
          }
        }
      },
    },
  }
}
